import React, { useState } from 'react';
import { Card, Tabs, Form, Input, Button, message } from 'antd';
import { resetPassword } from '@/services/auth';
import styles from './index.module.css';

const PersonalPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const handlePasswordReset = async (values: any) => {
    try {
      setLoading(true);
      const userEmail = JSON.parse(localStorage.getItem('user') || '{}').email;
      
      if (!userEmail) {
        message.error('获取用户信息失败，请重新登录');
        return;
      }
  
      await resetPassword({
        email: userEmail,
        old_password: values.oldPassword,
        new_password: values.newPassword,
      });
      
      message.success('密码修改成功');
      form.resetFields();
    } catch (error) {
      console.error('密码修改失败:', error);
      message.error('密码修改失败，请检查原密码是否正确');
    } finally {
      setLoading(false);
    }
  };

  const PasswordForm = () => (
    <Form
      form={form}
      layout="vertical"
      onFinish={handlePasswordReset}
      className={styles.form}
    >
      <Form.Item
        label="原密码"
        name="oldPassword"
        rules={[{ required: true, message: '请输入原密码' }]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item
        label="新密码"
        name="newPassword"
        rules={[{ required: true, message: '请输入新密码' }]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item
        label="确认新密码"
        name="confirmPassword"
        dependencies={['newPassword']}
        rules={[
          { required: true, message: '请确认新密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('newPassword') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致'));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading}>
          修改密码
        </Button>
      </Form.Item>
    </Form>
  );

  const items = [
    {
      key: 'profile',
      label: '个人信息',
      children: <div>个人信息内容</div>
    },
    {
      key: 'password',
      label: '修改密码',
      children: <PasswordForm />
    },
    {
      key: 'favorites',
      label: '我的收藏',
      children: <div>收藏列表</div>
    },
    {
      key: 'history',
      label: '浏览历史',
      children: <div>浏览历史列表</div>
    }
  ];

  return (
    <div className={styles.container}>
      <Card>
        <Tabs items={items} />
      </Card>
    </div>
  );
};

export default PersonalPage;